<?php
// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 检查数据库表状态
global $wpdb;
$stats_table = $wpdb->prefix . 'spider_stats';
$visits_table = $wpdb->prefix . 'spider_visits';

$visits_exists = $wpdb->get_var("SHOW TABLES LIKE '$visits_table'") == $visits_table;
$stats_exists = $wpdb->get_var("SHOW TABLES LIKE '$stats_table'") == $stats_table;
$tables_exist = $visits_exists && $stats_exists;

// 如果表不存在，尝试自动创建
if (!$tables_exist) {
    // 尝试创建表
    $charset_collate = $wpdb->get_charset_collate();
    
    // 蜘蛛访问记录表
    $sql1 = "CREATE TABLE $visits_table (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        spider_name varchar(100) NOT NULL,
        user_agent text NOT NULL,
        ip_address varchar(45) NOT NULL,
        url varchar(500) NOT NULL,
        referer varchar(500),
        visit_time datetime DEFAULT CURRENT_TIMESTAMP,
        response_code int(3) DEFAULT 200,
        response_time decimal(10,3),
        page_title varchar(255),
        PRIMARY KEY (id),
        KEY spider_name (spider_name),
        KEY visit_time (visit_time),
        KEY url (url(191))
    ) $charset_collate;";
    
    // 蜘蛛统计表
    $sql2 = "CREATE TABLE $stats_table (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        spider_name varchar(100) NOT NULL,
        visit_date date NOT NULL,
        visit_count int(11) DEFAULT 0,
        unique_pages int(11) DEFAULT 0,
        total_response_time decimal(10,3) DEFAULT 0,
        avg_response_time decimal(10,3) DEFAULT 0,
        last_visit datetime,
        PRIMARY KEY (id),
        UNIQUE KEY spider_date (spider_name, visit_date)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql1);
    dbDelta($sql2);
    
    // 再次检查表是否存在
    $visits_exists = $wpdb->get_var("SHOW TABLES LIKE '$visits_table'") == $visits_table;
    $stats_exists = $wpdb->get_var("SHOW TABLES LIKE '$stats_table'") == $stats_table;
    $tables_exist = $visits_exists && $stats_exists;
    
    if ($tables_exist) {
        update_option('wp_spider_monitor_tables_created', true);
    }
}

// 获取今日统计数据（只到当前小时）
$today = current_time('Y-m-d');
$current_hour = intval(current_time('H'));
$today_stats = array();
        $total_visits = 0;
        $total_spiders = 0;
        $total_pages = 0;
        $bot_type_stats = array();

        if ($tables_exist) {
            // 使用缓存机制优化数据库查询
            $cache_key = 'spider_today_stats_' . $today . '_' . $current_hour;
            $today_stats = get_transient($cache_key);
            
            if (false === $today_stats) {
                // 获取今天0点到当前小时的真实数据
                $today_stats = $wpdb->get_results($wpdb->prepare(
                    "SELECT 
                        spider_name,
                        COUNT(*) as visit_count,
                        COUNT(DISTINCT url) as unique_pages,
                        MAX(visit_time) as last_visit
                    FROM $visits_table 
                    WHERE DATE(visit_time) = %s AND HOUR(visit_time) <= %s
                    GROUP BY spider_name
                    ORDER BY visit_count DESC",
                    $today, $current_hour
                ), ARRAY_A);
                
                // 缓存5分钟
                set_transient($cache_key, $today_stats, 300);
            }

            // 缓存总访问数
            $total_visits_cache_key = 'spider_total_visits_' . $today . '_' . $current_hour;
            $total_visits = get_transient($total_visits_cache_key);
            if (false === $total_visits) {
                $total_visits = $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM $visits_table WHERE DATE(visit_time) = %s AND HOUR(visit_time) <= %s",
                    $today, $current_hour
                )) ?: 0;
                set_transient($total_visits_cache_key, $total_visits, 300);
            }

            $total_spiders = count($today_stats);
            
            // 缓存总页面数
            $total_pages_cache_key = 'spider_total_pages_' . $today . '_' . $current_hour;
            $total_pages = get_transient($total_pages_cache_key);
            if (false === $total_pages) {
                $total_pages = $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(DISTINCT url) FROM $visits_table WHERE DATE(visit_time) = %s AND HOUR(visit_time) <= %s",
                    $today, $current_hour
                )) ?: 0;
                set_transient($total_pages_cache_key, $total_pages, 300);
            }

            // 缓存bot类型统计
            $bot_type_cache_key = 'spider_bot_type_stats_' . $today . '_' . $current_hour;
            $bot_type_stats = get_transient($bot_type_cache_key);
            if (false === $bot_type_stats) {
                $bot_type_stats = $wpdb->get_results($wpdb->prepare(
                    "SELECT 
                        bot_type,
                        COUNT(*) as visit_count,
                        COUNT(DISTINCT spider_name) as spider_count,
                        COUNT(DISTINCT url) as unique_pages
                    FROM $visits_table 
                    WHERE DATE(visit_time) = %s AND HOUR(visit_time) <= %s
                    GROUP BY bot_type
                    ORDER BY visit_count DESC",
                    $today, $current_hour
                ), ARRAY_A);
                set_transient($bot_type_cache_key, $bot_type_stats, 300);
            }
        }
?>

<div class="wp-spider-monitor-container">
    <!-- 头部区域 -->
    <div class="spider-monitor-header">
        <div class="header-content">
            <div>
                <h1 class="header-title">🕷️ 蜘蛛监控中心</h1>
                <p class="header-subtitle">实时监控搜索引擎蜘蛛访问情况，优化网站SEO表现</p>
            </div>
            <div class="header-actions">
                <?php if (!$tables_exist): ?>
                    <button id="create-tables" class="btn btn-success">
                        <span>📊</span> 创建数据表
                    </button>
                <?php endif; ?>
                <button id="export-data" class="btn btn-secondary">
                    <span>📤</span> 导出数据
                </button>
                <button id="clear-data" class="btn btn-secondary">
                    <span>🗑️</span> 清理数据
                </button>
            </div>
        </div>
    </div>

    <!-- 主要内容区域 - 横向模块化布局 -->
    <div class="horizontal-dashboard">
        <!-- 主要统计区域 -->
        <div class="main-stats-section">
            <!-- 左侧大卡片 - 蜘蛛趋势 -->
            <div class="large-card trend-card">
                <div class="card-header">
                    <div class="header-left">
                        <h3 class="card-title">蜘蛛访问趋势</h3>
                        <div class="stats-summary">
                            <div class="stat-item">
                                <span class="stat-label">蜘蛛数</span>
                                <span class="stat-value"><?php echo $total_spiders; ?></span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">爬链数</span>
                                <span class="stat-value"><?php echo number_format($total_visits); ?></span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">平均爬链</span>
                                <span class="stat-value"><?php echo $total_spiders > 0 ? round($total_visits / $total_spiders) : 0; ?></span>
                            </div>
                        </div>
                    </div>
                    <div class="header-right">
                        <select class="time-selector">
                            <option value="today">今天</option>
                            <option value="week">本周</option>
                            <option value="month">本月</option>
                        </select>
                    </div>
                </div>
                <div class="card-content">
                    <div class="chart-container">
                        <canvas id="spider-trend-chart" width="600" height="300"></canvas>
                    </div>
                </div>
            </div>

            <!-- 右侧小卡片组 -->
            <div class="small-cards-group">
                <!-- 活跃蜘蛛卡片 -->
                <div class="small-card active-spiders-card">
                    <div class="card-header">
                        <h4 class="card-title">活跃蜘蛛</h4>
                        <div class="card-icon">🕷️</div>
                    </div>
                    <div class="card-content">
                        <div class="spider-list">
                            <?php if (!$tables_exist): ?>
                                <div class="no-data-message">
                                    <p>数据库表不存在，请先创建数据表</p>
                                </div>
                            <?php elseif (empty($today_stats)): ?>
                                <div class="no-data-message">
                                    <p>今日暂无蜘蛛访问记录</p>
                                </div>
                            <?php else: ?>
                                <?php 
                                // 只显示前3个最活跃的蜘蛛
                                $top_spiders = array_slice($today_stats, 0, 3);
                                foreach ($top_spiders as $stat): 
                                ?>
                                    <div class="spider-item" data-spider="<?php echo esc_attr($stat['spider_name']); ?>" onclick="showSpiderDetails('<?php echo esc_attr($stat['spider_name']); ?>')">
                                        <div class="spider-name"><?php echo esc_html($stat['spider_name']); ?></div>
                                        <div class="spider-count"><?php echo number_format($stat['visit_count']); ?></div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        <a href="<?php echo admin_url('admin.php?page=wp-spider-monitor-details'); ?>" class="view-more-link">查看详情 →</a>
                    </div>
                </div>

                <!-- Bot类型分析卡片 -->
                <div class="small-card bot-type-card">
                    <div class="card-header">
                        <h4 class="card-title">Bot类型分析</h4>
                        <div class="card-icon">📊</div>
                    </div>
                    <div class="card-content">
                        <div class="bot-type-list">
                            <?php if (!$tables_exist): ?>
                                <div class="no-data-message">
                                    <p>数据库表不存在</p>
                                </div>
                            <?php elseif (empty($bot_type_stats)): ?>
                                <div class="no-data-message">
                                    <p>暂无bot类型数据</p>
                                </div>
                            <?php else: ?>
                                <?php 
                                // 显示前3个bot类型
                                $top_types = array_slice($bot_type_stats, 0, 3);
                                foreach ($top_types as $type): 
                                    $type_name = get_bot_type_label($type['bot_type']);
                                ?>
                                    <div class="bot-type-item">
                                        <div class="type-name"><?php echo esc_html($type_name); ?></div>
                                        <div class="type-count"><?php echo number_format($type['visit_count']); ?></div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- 设置建议卡片 -->
                <div class="small-card suggestion-card">
                    <div class="card-header">
                        <h4 class="card-title">优化建议</h4>
                        <div class="notification-icon">🔔</div>
                    </div>
                    <div class="card-content">
                        <div class="suggestion-text">
                            建议将蜘蛛日志保留周期设置为30天，以提升插件性能。
                        </div>
                        <button class="explore-btn">立即设置</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 功能模块区域 -->
        <div class="features-section">
            <div class="feature-card">
                <div class="feature-icon">📊</div>
                <div class="feature-content">
                    <h4 class="feature-title">蜘蛛日志</h4>
                    <p class="feature-desc">爬取URL、时间、状态码、IP及蜘蛛名称等</p>
                </div>
            </div>

            <div class="feature-card">
                <div class="feature-icon">📋</div>
                <div class="feature-content">
                    <h4 class="feature-title">蜘蛛列表</h4>
                    <p class="feature-desc">蜘蛛清单、IP段、伪蜘蛛及拦截等</p>
                </div>
            </div>

            <div class="feature-card">
                <div class="feature-icon">🛤️</div>
                <div class="feature-content">
                    <h4 class="feature-title">访问路径</h4>
                    <p class="feature-desc">统观全站被爬取链接类型、次数及占比情况</p>
                </div>
            </div>

            <div class="feature-card">
                <div class="feature-icon">⚙️</div>
                <div class="feature-content">
                    <h4 class="feature-title">监控设置</h4>
                    <p class="feature-desc">配置监控参数、通知设置和数据保留策略</p>
                </div>
            </div>
        </div>

        <!-- 数据展示区域 -->
        <div class="data-section">
            <!-- 热门路径卡片 -->
            <div class="data-card popular-paths-card">
                <div class="card-header">
                    <h3 class="card-title">热门路径</h3>
                    <div class="card-controls">
                        <select class="time-selector">
                            <option value="today">今天</option>
                            <option value="week">本周</option>
                            <option value="month">本月</option>
                        </select>
                        <a href="#" class="view-more-link">查看更多 →</a>
                    </div>
                </div>
                <div class="card-content">
                    <div class="paths-visualization">
                        <div class="pie-chart-container">
                            <canvas id="paths-pie-chart" width="120" height="120"></canvas>
                        </div>
                        <div class="paths-table">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>访问路径</th>
                                        <th>爬取次数</th>
                                        <th>占比</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!$tables_exist): ?>
                                        <tr>
                                            <td colspan="3" class="no-data">数据库表不存在</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php
                                        // 获取热门路径数据（只到当前小时）
                                        $current_hour = intval(current_time('H'));
                                        $popular_paths = $wpdb->get_results($wpdb->prepare("
                                            SELECT 
                                                SUBSTRING_INDEX(url, '?', 1) as path,
                                                COUNT(*) as visit_count
                                            FROM {$wpdb->prefix}spider_visits 
                                            WHERE DATE(visit_time) = CURDATE() AND HOUR(visit_time) <= %d
                                            GROUP BY path
                                            ORDER BY visit_count DESC
                                            LIMIT 5
                                        ", $current_hour));
                                        
                                        if (empty($popular_paths)): ?>
                                            <tr>
                                                <td colspan="3" class="no-data">-- 暂无数据 --</td>
                                            </tr>
                                        <?php else: 
                                            $total_path_visits = array_sum(array_column($popular_paths, 'visit_count'));
                                            foreach ($popular_paths as $path): 
                                                $percentage = $total_path_visits > 0 ? round(($path->visit_count / $total_path_visits) * 100, 2) : 0;
                                        ?>
                                            <tr>
                                                <td><?php echo esc_html(strlen($path->path) > 20 ? substr($path->path, 0, 20) . '...' : $path->path); ?></td>
                                                <td><?php echo number_format($path->visit_count); ?></td>
                                                <td><?php echo $percentage; ?>%</td>
                                            </tr>
                                        <?php endforeach; endif; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 热门文章卡片 -->
            <div class="data-card popular-articles-card">
                <div class="card-header">
                    <h3 class="card-title">热门文章</h3>
                    <div class="card-controls">
                        <select class="time-selector">
                            <option value="today">今天</option>
                            <option value="week">本周</option>
                            <option value="month">本月</option>
                        </select>
                        <a href="#" class="view-more-link">查看更多 →</a>
                    </div>
                </div>
                <div class="card-content">
                    <div class="articles-table">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>文章</th>
                                    <th>蜘蛛访问量</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td colspan="2" class="no-data">-- 暂无数据 --</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 链接可访问性卡片 -->
            <div class="data-card link-accessibility-card">
                <div class="card-header">
                    <h3 class="card-title">链接可访问性</h3>
                    <div class="card-controls">
                        <select class="time-selector">
                            <option value="today">今天</option>
                            <option value="week">本周</option>
                            <option value="month">本月</option>
                        </select>
                        <a href="#" class="view-more-link">查看更多 →</a>
                    </div>
                </div>
                <div class="card-content">
                    <div class="status-codes-table">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>状态码</th>
                                    <th>数量</th>
                                </tr>
                            </thead>
                                <tbody>
                                    <?php if (!$tables_exist): ?>
                                        <tr>
                                            <td colspan="2" class="no-data">数据库表不存在</td>
                                        </tr>
                                    <?php else: ?>
                                        <?php
                                        // 获取状态码统计（只到当前小时）
                                        $current_hour = intval(current_time('H'));
                                        $status_codes = $wpdb->get_results($wpdb->prepare("
                                            SELECT 
                                                response_code,
                                                COUNT(*) as count
                                            FROM {$wpdb->prefix}spider_visits 
                                            WHERE DATE(visit_time) = CURDATE() AND HOUR(visit_time) <= %d
                                            GROUP BY response_code
                                            ORDER BY count DESC
                                            LIMIT 5
                                        ", $current_hour));
                                        
                                        if (empty($status_codes)): ?>
                                            <tr>
                                                <td colspan="2" class="no-data">-- 暂无数据 --</td>
                                            </tr>
                                        <?php else: 
                                            foreach ($status_codes as $status): ?>
                                            <tr>
                                                <td><?php echo esc_html($status->response_code); ?></td>
                                                <td><?php echo number_format($status->count); ?></td>
                                            </tr>
                                        <?php endforeach; endif; ?>
                                    <?php endif; ?>
                                </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部信息 -->
    <div class="dashboard-footer">
        <div class="footer-content">
            <div class="footer-brand">
                <span class="brand-icon">⚡</span>
                <span class="brand-text">Made By 闪电博</span>
            </div>
            <div class="footer-version">版本: <?php echo WP_SPIDER_MONITOR_VERSION; ?></div>
        </div>
        <div class="footer-links">
            <a href="#" class="footer-link">免费插件</a>
            <a href="#" class="footer-link">说明文档</a>
            <a href="#" class="footer-link">服务协议</a>
            <a href="#" class="footer-link">隐私条例</a>
        </div>
    </div>
<?php
    // Bot类型标签转换函数
    function get_bot_type_label($bot_type) {
        $labels = array(
            'search_engine' => '搜索引擎',
            'social_media' => '社交媒体',
            'seo_tools' => 'SEO工具',
            'archive' => '归档服务',
            'apple' => '苹果服务',
            'yahoo' => '雅虎服务',
            'unknown_bot' => '未知机器人',
            'unknown' => '未分类'
        );
        return isset($labels[$bot_type]) ? $labels[$bot_type] : $bot_type;
    }
    ?>

</div>

<style>
/* Bot类型分析卡片样式 */
.bot-type-list {
    margin-top: 15px;
}

.bot-type-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
}

.bot-type-item:last-child {
    border-bottom: none;
}

.bot-type-name {
    font-weight: 600;
    color: #495057;
    font-size: 14px;
}

.bot-type-count {
    color: #667eea;
    font-size: 14px;
    font-weight: 600;
}

/* 蜘蛛详情模态框增强样式 */
.spider-details-container {
    text-align: center;
}

.spider-header {
    margin-bottom: 25px;
}

.spider-header h3 {
    margin: 0 0 5px 0;
    font-size: 24px;
    color: #495057;
}

.spider-header p {
    margin: 0;
    color: #6c757d;
    font-size: 14px;
}

.spider-stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    margin-bottom: 30px;
}

.stat-item {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
}

.stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #667eea;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 14px;
    color: #6c757d;
    font-weight: 600;
}

.spider-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.2s ease;
}

.btn-primary {
    background: #667eea;
    color: white;
}

.btn-primary:hover {
    background: #5a6fd8;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #5a6268;
}
</style>

<!-- 蜘蛛详情模态框 -->
<div id="spider-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">蜘蛛访问详情</h2>
            <button class="modal-close" onclick="closeSpiderModal()">&times;</button>
        </div>
        <div id="spider-modal-content">
            <!-- 动态内容 -->
        </div>
    </div>
</div>

<script>
// 蜘蛛详情模态框
function showSpiderDetails(spiderName) {
    const modal = document.getElementById('spider-modal');
    const content = document.getElementById('spider-modal-content');
    
    content.innerHTML = '<div class="loading"></div> 加载中...';
    modal.classList.add('show');
    
    // 使用AJAX获取蜘蛛详情数据
    jQuery.post(
        ajaxurl,
        {
            action: 'spider_get_today_stats',
            spider_name: spiderName,
            nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
        },
        function(response) {
            if (response.success) {
                const data = response.data;
                content.innerHTML = `
                    <div class="spider-details-container">
                        <div class="spider-header">
                            <h3>${spiderName} 详细信息</h3>
                            <p>今日访问统计</p>
                        </div>
                        <div class="spider-stats-grid">
                            <div class="stat-item">
                                <div class="stat-value">${data.visit_count || 0}</div>
                                <div class="stat-label">访问次数</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value">${data.unique_pages || 0}</div>
                                <div class="stat-label">访问页面</div>
                            </div>
                            <div class="stat-item">
                                <div class="stat-value">${data.avg_response_time || 0}s</div>
                                <div class="stat-label">平均响应时间</div>
                            </div>
                        </div>
                        <div class="spider-actions">
                            <a href="${data.details_url || '#'}" class="btn btn-primary">查看完整详情</a>
                            <button class="btn btn-secondary" onclick="closeSpiderModal()">关闭</button>
                        </div>
                    </div>
                `;
            } else {
                content.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">⚠️</div>
                        <h3 class="empty-state-title">获取数据失败</h3>
                        <p class="empty-state-description">${response.data || '无法获取蜘蛛详情数据'}</p>
                    </div>
                `;
            }
        }
    ).fail(function() {
        content.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon">⚠️</div>
                <h3 class="empty-state-title">连接失败</h3>
                <p class="empty-state-description">无法连接到服务器，请稍后重试</p>
            </div>
        `;
    });
}

function closeSpiderModal() {
    document.getElementById('spider-modal').classList.remove('show');
}

function showUpgradeModal() {
    alert('Pro版功能正在开发中，敬请期待！');
}

// 绑定蜘蛛点击事件
document.addEventListener('DOMContentLoaded', function() {
    const spiderItems = document.querySelectorAll('.spider-item');
    spiderItems.forEach(item => {
        item.addEventListener('click', function() {
            const spiderName = this.dataset.spider;
            showSpiderDetails(spiderName);
        });
    });
});
</script>

<!-- 插件内部底部标志 -->
<div class="spider-footer">
    <div class="spider-footer-content">
        <a href="https://zibovip.top" target="_blank" class="spider-footer-logo">
            <span class="logo-text">小Z</span>
        </a>
    </div>
</div>